package main

import (
	"fmt"
	"io"
	"net"
	"time"

	"gitee.com/fcsvr/fancy/fcnet"
	"github.com/vmihailenco/msgpack/v5"
)

type Hello struct {
	S string
}

type User struct {
	ID       int
	Name     string
	Birthday time.Time
	Lv       int
	H        Hello
}

type Reply struct {
	Ret  int
	User *User
}

type GameRpc struct{}

func (this *GameRpc) AddUser(arg User, reply *Reply) error {
	return nil
}

func CliTest() {
	fmt.Println("Client Test, Start")

	conn, err := net.Dial("tcp", "127.0.0.1:7010")
	if err != nil {
		fmt.Println("client start err: ", err)
		return
	}

	user := User{
		ID:       1,
		Name:     "张三",
		Birthday: time.Date(2008, 11, 23, 0, 0, 0, 0, time.Local),
		Lv:       6,
		H: Hello{
			S: "Hello",
		},
	}

	//userByte, _ := json.Marshal(user)
	userByte, _ := msgpack.Marshal(user)
	fmt.Println(string(userByte))

	for {
		fmt.Println(string(userByte))
		pack := fcnet.NewPack()
		msg, _ := pack.Pack(fcnet.NewMsg(3, userByte))
		fmt.Println("write msg = ", msg)
		_, err := conn.Write(msg)
		if err != nil {
			fmt.Println("write err: ", err)
			return
		}

		readPack := fcnet.NewPack()
		fmt.Println("start to read head len = ", readPack.GetHeadLen())
		head := make([]byte, readPack.GetHeadLen())
		_, err = io.ReadFull(conn, head)
		if err != nil {
			fmt.Println("read head err", err)
			break
		}
		fmt.Println("head = ", head)
		msg2, err := pack.Unpack(head)
		if err != nil {
			fmt.Println("unpack head err", err)
			return
		}

		fmt.Printf("msg data len = %d\n", msg2.GetDataLen())
		fmt.Printf("msg id = %d\n", msg2.GetHead().(fcnet.Head).GetID())
		fmt.Printf("msg typ = %d\n", msg2.GetHead().(fcnet.Head).GetTyp())
		fmt.Printf("msg codectyp = %d\n", msg2.GetHead().(fcnet.Head).GetCodecTyp())
		fmt.Printf("msg version = %d\n", msg2.GetHead().(fcnet.Head).GetVersion())
		if msg2.GetDataLen() > 0 {
			//msg := msgHead.(*fcnet.Msg)
			msg2.Data = make([]byte, msg2.GetDataLen())

			_, err := io.ReadFull(conn, msg2.Data)
			if err != nil {
				fmt.Println("server unpack err: ", err)
				return
			}
			u := &Reply{
				User: &User{},
			}
			fmt.Println(string(msg2.Data))
			err = msgpack.Unmarshal(msg2.Data, u)
			fmt.Println(err)
			//fmt.Println("recv msg id = ", msg.ID, ", len = ", msg.DataLen, ", data = ", string(msg.Data))
			fmt.Println("recv msg2 id = ", msg2.ID, ", len = ", msg2.DataLen, ", data = ", u.User)
		}
		time.Sleep(time.Millisecond)
	}
}

func main() {
	go CliTest()
	for {
		time.Sleep(10 * time.Second)
	}
}
